from functools import wraps
from fastapi import HTTPException, Depends
from sqlalchemy.orm import Session
from app.db.session import get_db
from app.db.models.user import User
from app.db.models.chat import Room, RoomMember
from app.utils.security import get_current_user

def verify_room_access(room_id_param: str = "roomId"):
    """验证用户对房间的访问权限的装饰器
    
    Args:
        room_id_param: 请求中房间ID的参数名
    """
    def decorator(func):
        @wraps(func)
        async def wrapper(*args, **kwargs):
            # 获取room_id
            room_id = kwargs.get(room_id_param)
            if not room_id:
                # 尝试从查询参数获取
                request = kwargs.get("request")
                if request and hasattr(request, "query_params"):
                    room_id = request.query_params.get(room_id_param)
            
            if not room_id:
                raise HTTPException(status_code=400, detail={"message": f"缺少参数 {room_id_param}"})
            
            # 获取当前用户
            current_user = kwargs.get("current_user")
            if not current_user:
                # 如果没有提供，尝试获取
                current_user = Depends(get_current_user)
            
            # 获取数据库会话
            db = kwargs.get("db")
            if not db:
                # 如果没有提供，尝试获取
                db = next(get_db())
            
            # 验证房间存在
            room = db.query(Room).filter(Room.id == room_id).first()
            if not room:
                raise HTTPException(status_code=404, detail={"message": "会话房间不存在"})
            
            # 验证用户是否有权限访问该房间
            room_member = db.query(RoomMember).filter(
                RoomMember.room_id == room_id,
                RoomMember.user_id == current_user.id
            ).first()
            
            if not room_member:
                raise HTTPException(status_code=403, detail={"message": "无权访问此会话"})
            
            # 添加房间和成员信息到kwargs
            kwargs["room"] = room
            kwargs["room_member"] = room_member
            
            return await func(*args, **kwargs)
        return wrapper
    return decorator 